package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result listShopType() {
        //查询缓存
        String shopTypeStr = stringRedisTemplate.opsForValue().get("cache:shopType");
        if(StringUtils.isNotBlank(shopTypeStr)){
            return Result.ok(JSONUtil.toList(shopTypeStr, ShopType.class));
        }
        //查询列表
        List<ShopType> shopTypes = this.query().orderByAsc("sort").list();
        if (shopTypes == null) {
            return Result.fail("店铺类型不存在");
        }
        String jsonStr = JSONUtil.toJsonStr(shopTypes);
        //存入缓存
        stringRedisTemplate.opsForValue().set("cache:shopType",jsonStr);
        return Result.ok(shopTypes);
    }
}
